{layout name="layout" /}
<blockquote class="layui-elem-quote layui-quote-nm">
    <p>使用说明-注册：</p>
    <p>请求url：http://yourdomain/api/v1/reg</p>
    <p>请求参数：username | password</p>
</blockquote>
<blockquote class="layui-elem-quote layui-quote-nm">
    <p>使用说明-登录：</p>
    <p>请求url：http://localhost:81/api/v1/login</p>
    <p>请求参数：username | password</p>
    <p>Header头参数：did 设备唯一标识 | version 版本号</p>
</blockquote>
<blockquote class="layui-elem-quote layui-quote-nm">
    <p>使用说明-授权访问（demo）：</p>
    <p>请求url：http://localhost:81/api/v1/userg</p>
    <p>Header头参数：did 设备唯一标识 | version 版本号 | token 登录获取的密钥 | time 登录获取的时间戳</p>
</blockquote>
<style>
    /*自适应行高，但设置后不可以使用固定列，否则会样式错乱*/
    .layui-table-cell {
        height: inherit;
    }
</style>
<table class="layui-hide" id="test" lay-filter="test"></table>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="addUser">添加</button>
        <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="getCheckData">删除选中行</button>
        <!--        <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>-->
        <!--        <button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>-->
    </div>
</script>

<script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="edit">重置密码</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 -->
<script type="text/html" id="statusTpl">
    <input type="checkbox" name="status" value="{{d.id}}" lay-skin="switch" lay-text="启用|禁止" lay-filter="status" {{ d.status == 1 ? 'checked' : '' }}>
</script>

<script>
    layui.use(['table','util'], function(){
        var table = layui.table;
        var util = layui.util;
        var form = layui.form;

        table.render({
            elem: '#test'
            ,url:'/admin/user/getUserListJson'
            ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                title: '提示'
                ,layEvent: 'LAYTABLE_TIPS'
                ,icon: 'layui-icon-tips'
            }]
            ,title: '菜单列表'
            ,cols: [[
                {type: 'checkbox'}
                ,{field:'id', title:'ID', width:80, unresize: true, sort: true}
                ,{field:'username', title:'用户名',width:120, sort: true}
                ,{field:'type_id', title:'用户组ID', edit:'text',width:100, sort: true}
                ,{field:'user_group', title:'用户组',width:100, sort: true,templet: function(res){
                        return res.user_group.group_name;
                    }}
                ,{field:'password', title:'密码',width:120, sort: true}
                ,{field:'avatar_src', title:'头像', event: 'editAvatar',width:200,height:100, templet: function(res){
                        return '<img width="50" height="50" src="'+res.avatar_src+'" />'
                    }}
                ,{field:'email', title:'邮箱', edit:'text',width:150}
                ,{field:'mobile', title:'电话', edit:'text',width:150, unresize: true}
                ,{field:'status', title:'状态', width:120,templet: '#statusTpl', unresize: true}
                ,{field:'create_ip', title:'创建IP', edit:'text',width:150}
                ,{field:'create_time', title:'创建时间', width:180}
                ,{field:'update_time', title:'最后操作时间', width:120} //每次登录时更新该时间
                ,{title:'操作', toolbar: '#barDemo', width:160}
            ]]
            ,page: true
            ,limit: 20 //默认每页显示条数
        });


        //监听状态操作
        form.on('switch(status)', function(obj){
            console.log('id:'+this.value,'key:'+this.name,'value:'+obj.elem.checked, obj.othis);
            //调用修改权重接口
            var value = obj.elem.checked ? 1:0;
            var editData = [
                {
                    'id':this.value,
                    [this.name]:value
                }
            ];
            $.ajax({
                url: "/admin/user/editList",
                type: "POST",
                data:{
                    'editArray':editData,
                },
                dataType: "json",
                success: function(result){
                    console.log(result)
                    if(result.code === 0){
                        layer.msg(result.msg);
                    }
                },
                error:function(err){
                    console.log(err.statusText);
                }
            });
        });


        //头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'getCheckData':
                    var data = checkStatus.data;
                    var idArray=[];
                    data.filter(item =>{
                        idArray.push(item.id);
                    })
                    layer.confirm('真的删除行么', function(index){
                        //layer.alert(JSON.stringify(data));
                        console.log('idArray:',idArray);
                        layer.close(index);
                        //调用删除接口
                        $.ajax({
                            url: "/admin/user/del",
                            type: "POST",
                            data:{
                                'idArray':idArray
                            },
                            dataType: "json",
                            success: function(result){
                                console.log(result)
                                if(result.code === 0){
                                    layer.msg(result.msg);
                                    location.reload();
                                }
                            },
                            error:function(err){
                                console.log(err.statusText);
                            }
                        });
                    });
                    break;
                case 'getCheckLength':
                    var data = checkStatus.data;
                    layer.msg('选中了：'+ data.length + ' 个');
                    break;
                case 'isAll':
                    layer.msg(checkStatus.isAll ? '全选': '未全选');
                    break;
                case 'addUser':
                    window.open('/admin/user/add');
                    break;

                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;
            };
        });

        //监听单元格编辑
        table.on('edit(test)', function(obj){
            var value = obj.value //得到修改后的值
                ,data = obj.data //得到所在行所有键值
                ,field = obj.field; //得到字段
            if(field === 'sort'){
                if (!(/(^[1-9]\d*$)/.test(util.escape(value)))) {
                    layer.msg('输入值无效，请输入非零开头的正整数');
                    return false;
                }
            }
            console.log('[ID: '+ data.id +'] ' + field + ' 字段更改值为：'+ util.escape(value));
            var editData = [
                {
                    'id':data.id,
                    [field]:util.escape(value)
                }
            ];
            console.log(editData);
            //调用修改权重接口
            $.ajax({
                url: "/admin/user/editList",
                type: "POST",
                data:{
                    'editArray':editData,
                },
                dataType: "json",
                success: function(result){
                    console.log(result)
                    if(result.code === 0){
                        layer.msg(result.msg);
                    }
                },
                error:function(err){
                    console.log(err.statusText);
                }
            });
        });

        //监听行工具事件
        table.on('tool(test)', function(obj){
            var data = obj.data;
            console.log(obj.event)
            if(obj.event === 'del'){
                var idArray=[];
                idArray.push(data.id);
                layer.confirm('真的删除行么', function(index){
                    console.log("删除:"+idArray);
                    obj.del();
                    layer.close(index);
                    //调用删除接口
                    $.ajax({
                        url: "/admin/user/del",
                        type: "POST",
                        data:{
                            'idArray':idArray
                        },
                        dataType: "json",
                        success: function(result){
                            console.log(result)
                            if(result.code === 0){
                                layer.msg(result.msg);
                                location.reload();
                            }
                        },
                        error:function(err){
                            console.log(err.statusText);
                        }
                    });
                });
            } else if(obj.event === 'edit'){
                layer.prompt({
                    formType: 1
                    ,value: data.password
                }, function(value, index){
                    var editData = [
                        {
                            'id':data.id,
                            'password':value
                        }
                    ];
                    //调用修改密码接口
                    $.ajax({
                        url: "/admin/user/editList",
                        type: "POST",
                        data:{
                            'editArray':editData,
                        },
                        dataType: "json",
                        success: function(result){
                            console.log(result)
                            if(result.code === 0){
                                layer.msg(result.msg);
                            }
                        },
                        error:function(err){
                            console.log(err.statusText);
                        }
                    });
                    layer.close(index);
                });
            } else if(obj.event === 'editAvatar'){
                layer.open({
                    type: 2,
                    title: '修改头像',
                    closeBtn: 1,
                    shadeClose: false,
                    area: ['288px', '500px'],
                    content:'editAvatar/id/'+data.id
                });
            }
        });
    });
</script>
